package com.sumfun.blog.aspect;

import com.sumfun.blog.annotation.RequireLogin;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.utils.LoginUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录校验 AOP
 *
 * @author sumfun
 * @date 2024-04-21
 */
@Aspect
@Component
public class LoginCheckAspect {

    @Autowired
    private LoginUtils loginUtils;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param requireLogin
     * @return
     */
    @Around("@annotation(requireLogin)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, RequireLogin requireLogin) throws Throwable {
        // 获取 request
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 判断是否登录
        if (!loginUtils.isLogin(request)) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        // 通过验证，放行
        return joinPoint.proceed();
    }
}